import router from '@/router'
import store from '@/store'
router.beforeEach(async(to, from, next) => {
  // 要去的地方
  const url = to.path
  // token
  console.log(store.getters)
  const token = store.getters.token
  // 白名单
  const whiteList = ['/login', '/404', '/test']

  if (token && url === '/login') {
    // 1.有token登录过。去首页拦截
    next('/')
  }
  if (token && url !== '/login') {
    // 2.有token登录过，不去登录页放行
    if (!store.getters.name) {
      await store.dispatch('user/getUserInfo')
      const res = await store.dispatch('permission/filterRoutes', store.getters.menus)
      router.addRoutes([...res,
        // 404 page must be placed at the end !!!
        { path: '*', redirect: '/404', hidden: true }
      ])
      return next(to.path)
    }
    next()
  }
  if (!token && whiteList.indexOf(url) > -1) {
    // 3.没有token登录过，在白名单放行
    next()
  }
  if (!token && whiteList.indexOf(url) === -1) {
    // 4.没有token登录过，不在白名单，拦截
    next('/login')
  }
})
